import requests
import keyring
import yagmail
import time
from imbox import Imbox


def get_verse():
    url = 'https://v2.jinrishici.com/one.json?client=browser-sdk/1.2?client=browser-sdk/1.2'
    response = requests.get(url)
    response.encoding = 'UTF-8'
    #  解析诗词

    return f'您要的每日诗词是：{response.json()["data"]["content"]}'


def get_weather(city):
    url = f'http://wthrcdn.etouch.cn/weather_mini?city={city}'
    response = requests.get(url).json()
    results = response['data']['forecast'][0]
    return f'{city}今天的天气情况为{results["type"]}，{results["high"][:-1]}度，{results["low"][:-1]}度'


password = keyring.get_password('qqmail', '1769699920')


# 发送邮件
def send_mail(email, results):
    mail = yagmail.SMTP(user='1769699920@qq.com', password=password, host='smtp.qq.com')
    contents = [results]
    mail.send(email, '【自动回复】您要的信息见正文', contents)


def main():
    print('执行main----')
    with Imbox('imap.qq.com', '1769699920@qq.com', password, ssl=True) as imbox:
        unread_inbox_messages = imbox.messages(unread=True)
        for uid, message in unread_inbox_messages:
            title = message.subject
            email = message.sent_from[0]['email']
            results = ''
            if title == '来句诗':
                results = get_verse()
            if title == '天气':
                results = get_weather('珠海')
            if results:
                send_mail(email, results)
                imbox.mark_seen(uid)


# 循环
while True:
    main()
    time.sleep(5)
